<template>
  <div class="main-container custom-el-plus">
    <div class="top-search-box">
      <el-input
        v-model="state.searchText"
        style="width: 360px"
        placeholder="请输入任务名称或编号"
        :suffix-icon="Search"
      />
      <el-button type="primary" @click="searchTask">查询</el-button>
      <el-button plain @click="resetSearch">重置</el-button>
    </div>
    <div class="bottom-box">
      <div class="bottom-inner-box">
        <div class="bottom-head-box">
          <div class="head-icon"></div>
          <p class="head-title">任务列表</p>
          <el-button plain @click="addtask">+ 新增</el-button>
          <el-button plain @click="showEventTypePage">事件类型管理</el-button>
        </div>
        <div class="table-box">
          <el-table
            :data="state.taskList"
            style="width: 100%"
            class="style-table"
          >
            <el-table-column
              type="index"
              :index="getIndex"
              label="序号"
              width="80"
            />
            <el-table-column
              prop="taskName"
              label="任务名称"
              width="200"
              show-overflow-tooltip
            />
            <el-table-column prop="pkId" label="任务编号" width="200" />
            <el-table-column prop="createUser" label="创建人" />
            <el-table-column prop="startup" label="任务状态">
              <template #default="props">
                <div :class="props.row.startup ? 'enable-box' : 'unable-box'">
                  {{ props.row.startup ? "启用" : "停用" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="isAuto" label="自动任务">
              <template #default="props">
                <span>{{ props.row.isAuto ? "是" : "否" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="autoStartTime" label="自启时间">
              <template #default="props">
                {{ props.row.isAuto ? props.row.autoStartTime : "-" }}
              </template> </el-table-column
            >>
            <el-table-column prop="autoEndTime" label="自停时间">
              <template #default="props">
                {{ props.row.isAuto ? props.row.autoEndTime : "-" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="description"
              label="任务描述"
              width="400"
              show-overflow-tooltip
            />
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <div class="task-btn-box">
                  <el-switch
                    size="small"
                    :active-value="1"
                    :inactive-value="0"
                    v-model="scope.row.startup"
                    :before-change="beforeUpdate.bind(this, scope.row)"
                  />
                  <span class="statu-label">{{
                    scope.row.startup ? "启用" : "停用"
                  }}</span>
                  <span
                    class="btn-check"
                    v-if="!scope.row.editFlag"
                    @click="checkTask(scope.row)"
                    >查看</span
                  >
                  <span class="btn-edit" @click="editDeviceInfo(scope.row)"
                    >编辑</span
                  >
                  <span class="btn-shutdown" @click="deleteTask(scope.row)"
                    >删除</span
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page-box">
          <el-pagination
            style="margin-left: auto"
            v-model:current-page="state.currentPage"
            :page-size="state.pageSize"
            :small="small"
            :background="true"
            layout="total, prev, pager, next"
            :total="state.totalTaskNum"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <eventComp v-model:eventShow="state.eventTypeShow"></eventComp>
    <addTaskComp
      v-model:taskShow="state.showAddTaskDialog"
      @change="reflashTaskList"
    ></addTaskComp>
    <editTaskComp
      v-model:taskShow="state.showTaskDialog"
      :taskCode="state.taskCode"
      @change="reflashTaskList"
    ></editTaskComp>
    <checkTaskComp
      v-model:taskInfo="state.showCheckTaskDialog"
      :taskCode="state.taskCode"
    ></checkTaskComp>
  </div>
</template>

<script setup>
import {
  computed,
  watch,
  getCurrentInstance,
  onActivated,
  onBeforeUnmount,
  onDeactivated,
  onMounted,
  reactive,
  ref,
  h,
  nextTick,
  defineProps,
} from "vue";
import { useRoute } from "vue-router";
import { Search } from "@element-plus/icons-vue";
import addTaskComp from "./addTaskDialog.vue";
import editTaskComp from "./editTaskDialog.vue";
import checkTaskComp from "./checkTaskDialog.vue";
import eventComp from "./eventDialog.vue";
// import { taskList } from "./mockData.js";
import { ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
const { proxy } = getCurrentInstance();
/* ====================================声明变量================================= */
const state = reactive({
  searchText: "",
  taskName: "",
  pkId: null,
  taskList: [],
  currentPage: 1,
  pageSize: 15,
  totalTaskNum: 0,
  eventTypeShow: false,
  currentEventPage: 1,
  showAddTaskDialog: false,
  showTaskDialog: false,
  showCheckTaskDialog: false,
  taskCode: "",
});
/* ====================================事件方法================================= */
const beforeUpdate = (row) => {
  return new Promise((resolve, reject) => {
    row.updateLoading = true;
    editTaskStatus({
      pkId: row.pkId,
      startup: !row.startup ? 1 : 0,
    })
      .then((res) => {
        let status = "";
        if (row.startup) {
          status = "停用";
        } else {
          status = "启用";
        }
        ElMessage({
          message: `任务${status}成功`,
          type: "success",
        });
        return resolve(true);
      })
      .catch((error) => {
        let status = "";
        if (row.startup) {
          status = "停用";
        } else {
          status = "启用";
        }
        ElMessage({
          message: `任务${status}失败`,
          type: "error",
        });
        return reject();
      })
      .finally(() => {
        row.updateLoading = false;
      });
  });
};
const deleteTask = (row) => {
  ElMessageBox({
    title: "",
    cancelButtonClass: "messagebox-cancel-btn",
    confirmButtonClass: "messagebox-confirm-btn",
    customStyle: {
      backgroundColor: "#0D172F",
      borderRadius: "8px",
    },
    message: h("p", null, [
      h("div", { style: "color: #A5ADBA; margin: 2.781vh 0 3.708vh 0.624vw" }, "确认删除此任务?"),
    ]),
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "loading...";
        deleteTaskById(row.pkId)
          .then((res) => {
            ElMessage({
              message: "删除任务成功",
              type: "success",
            });
            done();
            instance.confirmButtonLoading = false;
            getTaskList({
              pageNum: state.currentPage,
              taskName: state.taskName,
              pkId: state.pkId,
            }).then((res) => {
              state.totalTaskNum = res.total;
              state.taskList = res.list;
            });
          })
          .catch((err) => {
            ElMessage({
              message: "删除任务失败",
              type: "error",
            });
            instance.confirmButtonLoading = false;
          });
      } else {
        done();
      }
    },
  }).then((action) => {});
};
const reflashTaskList = (row) => {
  getTaskList({
    pageNum: state.currentPage,
    taskName: state.taskName,
    pkId: state.pkId,
  }).then((res) => {
    state.totalTaskNum = res.total;
    state.taskList = res.list;
  });
};
const editDeviceInfo = (row) => {
  state.taskCode = "";
  state.showTaskDialog = true;
  nextTick(() => {
    state.taskCode = row.pkId;
  });
};
const checkTask = (row) => {
  state.taskCode = "";
  state.showCheckTaskDialog = true;
  nextTick(() => {
    state.taskCode = row.pkId;
  });
};
const addtask = () => {
  state.showAddTaskDialog = true;
};
const showEventTypePage = () => {
  state.eventTypeShow = true;
};
const handleCurrentChange = (val) => {
  getTaskList({
    pageNum: state.currentPage,
    taskName: state.taskName,
    pkId: state.pkId,
  }).then((res) => {
    state.totalTaskNum = res.total;
    state.taskList = res.list;
  });
};
const getIndex = (index) => {
  return (state.currentPage - 1) * state.pageSize + index < 9
    ? "0" + ((state.currentPage - 1) * state.pageSize + (index + 1))
    : (state.currentPage - 1) * state.pageSize + (index + 1);
};
const resetSearch = () => {
  state.searchText = "";
  nextTick(() => {
    getTaskList({
      pageNum: state.currentPage,
      taskName: state.taskName,
      pkId: state.pkId,
    }).then((res) => {
      state.totalTaskNum = res.total;
      state.taskList = res.list;
    });
  });
};
const searchTask = () => {
  getTaskList({
    pageNum: state.currentPage,
    taskName: state.taskName,
    pkId: state.pkId,
  }).then((res) => {
    state.totalTaskNum = res.total;
    state.taskList = res.list;
  });
};
/* ====================================自定义方法================================= */
const isNumber = (value) => {
  return typeof value === "number" && !isNaN(value);
};
/* ====================================接口方法================================= */
const editTaskStatus = async (param) => {
  const res = await proxy.$http.postWithBody("alarm/task/update", param);
  if (res == 0) {
    throw res;
  }
  return res;
};
const deleteTaskById = async (pkId) => {
  const res = await proxy.$http.getFun(`alarm/task/deleteByPkId/${pkId}`);
  if (JSON.stringify(res) == "{}") {
    throw res;
  }
  return res;
};
const getTaskList = async (param) => {
  const res = await proxy.$http.postWithBody(
    "alarm/task/selectAll",
    Object.assign(
      {
        pageNum: 1,
        pageSize: state.pageSize,
        taskName: "",
        pkId: null,
      },
      param
    )
  );
  if (JSON.stringify(res) == "{}") {
    throw res;
  }
  return res;
};
watch(
  () => state.searchText,
  (newVal, oldVal) => {
    state.taskName = "";
    state.pkId = null;
    if (newVal) {
      if (isNumber(+newVal)) {
        state.pkId = newVal;
      } else {
        state.taskName = newVal;
      }
    }
  },
  {
    immediate: true,
  }
);
const handleBeforeUnload = () => {
  sessionStorage.removeItem("detailTask");
};
onMounted(() => {
  window.addEventListener("beforeunload", handleBeforeUnload);
  if (sessionStorage.getItem("detailTask")) {
    state.searchText = sessionStorage.getItem("detailTask");
  } else {
    getTaskList().then((res) => {
      state.totalTaskNum = res.total;
      state.taskList = res.list;
    });
  }
});
onBeforeUnmount(() => {
  handleBeforeUnload();
});
</script>

<style scoped lang="scss">
.main-container {
  background-color: #000102;
  padding: 0 !important;
  & > .top-search-box {
    height: pxTvh(88);
    margin: pxTvh(24) pxTvw(24) 0 pxTvw(24);
    background: #0d172f;
    border-radius: 4px;
    @include elasticFN(flex-start, center);
    & > .el-input {
      margin-left: pxTvw(16);
    }
    & > .el-button:nth-of-type(1) {
      margin-left: auto;
    }
    & > .el-button:nth-of-type(2) {
      margin-right: pxTvw(24);
      margin-left: pxTvw(16);
    }
  }
  & > .bottom-box {
    margin: pxTvh(16) pxTvw(8) 0 pxTvw(8);
    height: calc(100% - #{pxTvh(128)});
    // background: red;
    overflow-y: auto;
    & > .bottom-inner-box {
      background: #0d172f;
      border-radius: 4px;
      margin: 0 pxTvw(13) pxTvh(24) pxTvw(16);
      padding: pxTvh(20) 0 pxTvh(24) 0;
      & > .bottom-head-box {
        height: pxTvh(40);
        margin: 0 pxTvw(16) 0 pxTvw(16);
        @include elasticFN(flex-start, center);
        & > .head-icon {
          width: pxTvw(4);
          height: pxTvh(13);
          background: #3174ff;
        }
        & > .head-title {
          font-family: PingFang SC, PingFang SC,sans-serif;
          font-weight: 500;
          @include computed_font(18);
          color: #e8f1ff;
          margin-left: pxTvw(8);
        }
        & > .el-button:nth-of-type(1) {
          margin-left: auto;
        }
      }
      & > .table-box {
        margin: pxTvh(16) pxTvw(16) 0 pxTvw(16);
      }
      & > .page-box {
        margin: pxTvh(16) pxTvw(16) 0 pxTvw(16);
      }
    }
  }
}
.task-btn-box {
  color: #377dff;
  display: flex;
  & > .statu-label {
    margin-left: pxTvw(8);
    color: #d3dfff;
  }
  & > .btn-check {
    cursor: pointer;
    margin-left: pxTvw(16);
  }
  & > .btn-edit {
    cursor: pointer;
    margin-left: pxTvw(16);
  }
  & > .btn-shutdown {
    cursor: pointer;
    color: #e04f3f;
    margin-left: pxTvw(16);
  }
}
.event-descrition,
.task-descrition {
  @include overstepForRow();
}
.enable-box {
  width: pxTvw(56);
  height: pxTvh(24);
  border-radius: pxTvw(12);
  border: 1px solid #34ad54;
  color: #34ad54;
  @include elasticFN(center, center);
}
.unable-box {
  width: pxTvw(56);
  height: pxTvh(24);
  border-radius: pxTvw(12);
  border: 1px solid #a5adba;
  color: #a5adba;
  @include elasticFN(center, center);
}
</style>
<style lang="scss">

</style>
